import os
import gtk
import gtk.glade
import pango
from BuildWizException import BuildWizException

class ScriptWindow:
    def __init__( self, gladefile, wizard, scriptfile):
        self.__glade = gladefile
        self.__scriptFile = scriptfile
        self.__fdScript = None
        self.__wiz = wizard
        self.__xml = gtk.glade.XML( self.__glade)
        self.__originalFileContents = ""
        if self.__xml:
            self.__win = self.__xml.get_widget( "ScriptWindow")
            self.__win.hide()
            self.__win.set_title( os.path.split( self.__scriptFile)[ 1])
            self.__handlers = { "on_btnOk_clicked": self.__onOK
                              , "on_btnCancel_clicked": self.__onCancel 
                              , "on_fontbutton_font_set": self.__fontChanged}
            self.__win.connect( "destroy", lambda w: self.__win.destroy())
            self.__xml.signal_autoconnect( self.__handlers)
            self.__txtViewScript = self.__xml.get_widget( "txtviewScript")
            self.__buffer = self.__txtViewScript.get_buffer()
            self.__openScript()

    def show( self):
        self.__win.show_all()

    def __openScript( self):
        try:
            if os.path.isfile( self.__scriptFile):
                self.__fdScript = open( self.__scriptFile, "r")
                self.__originalFileContents = self.__fdScript.read()
                self.__fdScript.close()

            self.__fdScript = open( self.__scriptFile, "w")
            self.__buffer.set_text( self.__originalFileContents)
            self.__isOpen = True

        except IOError, error:
            self.__isOpen = False
            raise BuildWizException( "Could not open [" + self.__scriptFile + "]")

    def __onCancel( self, button):
        try:
            
            if self.__isOpen:
                print "ScriptWindow.onCancel() is open"
                self.__fdScript.write( self.__originalFileContents)
                self.__fdScript.close()
        except IOError:
            pass

        self.__win.destroy()

    def __onOK( self, button):
        start = self.__buffer.get_start_iter()
        end = self.__buffer.get_end_iter()
        try:
            print "ScriptWindow.onCancel() try to write"
            self.__fdScript.write( self.__buffer.get_text( start, end))
            self.__fdScript.close()
            self.__win.destroy()
        except IOError:
            pass


    def __fontChanged( self, fontbutton):
        fontdesc = fontbutton.get_font_name()
        self.__txtViewScript.modify_font( pango.FontDescription( fontdesc))

